"""
请求报文格式
    请求方法+空格+url+空格+协议版本+换行符

响应报文格式
    协议版本+空格+状态码+空格+状态描述符+换行符

web服务器的主要工作：解析http报文
"""
import socket

MSG = """\
HTTP/1.1 200 OK

Hello, World!
"""


def demo_app(environs, start_response):
    for k, v in environs.items():
        print(k, '=', repr(v))
    start_response("200 OK", [('Content-Type', 'text/plain; charset=utf-8')])
    return [b'request success']


def run_server(application):
    server = socket.socket()
    server.bind(('localhost', 8088))
    server.listen(1)
    print('server is running...')

    while True:
        client_socket, client_address = server.accept()
        request = client_socket.recv(1024)

        messages = request.decode('utf-8').split('\r\n')
        method, path, protocol = messages.pop(0).split(' ')
        environ = {
            'REQUEST_METHOD': method,
            'SCRIPT_NAME': path,
            'SERVER_PROTOCOL': protocol,
        }
        for message in messages:
            m = message.split(': ')
            print(m)
            # environ[k] = v

        response_data = b''

        def start_response(status, response_headers, exc_info=None):
            """
            :params status: 指HTTP的状态字符串如`200 OK`,`404 Not Found`
            :params response_headers: 是一个形如(header_name, header_value)的元组列表
            :params exc_info: sys.exc_info()返回的 tuple: (type, value, traceback)
            :return write()
            """
            data = f'{protocol} {status}\r\n'
            for k, v in response_headers:
                data += f'{k}:v\r\n'
            data += '\n'

            nonlocal response_data
            response_data = data.encode('utf=8')

            return 'write()'

        result = application(environ, start_response)
        for content in result:
            resp = response_data + content
            client_socket.sendall(resp)

        client_socket.close()


if __name__ == '__main__':
    run_server(demo_app)
